package com.ruoyi.quartz.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.FlaskDiagnosisConstants;
import com.ruoyi.common.constant.FlaskModelConstants;
import com.ruoyi.common.constant.ScheduleConstants;
import com.ruoyi.common.exception.job.TaskException;
import com.ruoyi.common.utils.flask.HttpFlask;
import com.ruoyi.quartz.domain.SysJob;
import com.ruoyi.quartz.mapper.SysJobMapper;
import com.ruoyi.quartz.service.IModelFileService;
import com.ruoyi.quartz.service.ISysJobService;
import com.ruoyi.quartz.util.CronUtils;
import com.ruoyi.quartz.util.ScheduleUtils;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.List;

/**
 * 定时任务处理文件，需要连接算法服务器
 */
@Service
public class ModelFileServiceImpl implements IModelFileService {
    public Boolean clearFileCache() {
        String res = HttpFlask.sendGetFlask(FlaskModelConstants.Model_CSV_URL);
        return clearCache(res);
    }

    public Boolean clearTestFileCache() {
        String res = HttpFlask.sendGetFlask(FlaskModelConstants.Model_TEST_FILE_URL);
        return clearCache(res);
    }

    private Boolean clearCache(String res) {
        if (!"".equals(res)) {
            JSONObject jsonObject = JSONObject.parseObject(res);
            String csvDir = (String) jsonObject.get("data");
            File directory = new File(csvDir);
            if (directory.exists()) {
                deleteFiles(directory);
                makeDir(csvDir);
                return directory.exists();
            }
        }
        return false;
    }

    private void deleteFiles(File directory) {
        if (directory.isDirectory()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    deleteFiles(file);
                }
            }
        }
        directory.delete();
    }

    private void makeDir(String csvDir) {
        File dir = new File(csvDir);
        dir.mkdir();
    }
}
